import React, { useLayoutEffect, useState } from "react";
import { TabBar } from "antd-mobile";
import styles from "./index.module.scss";
import {
  AppOutline,
  UnorderedListOutline,
  UserOutline,
} from "antd-mobile-icons";
import { useLocation, useNavigate } from "react-router-dom";

type Props = {};

export default function index({}: Props) {
  const navigate = useNavigate();
  const location = useLocation();

  // 控制tabbar显隐
  const [visiable, setVisiable] = useState<boolean>(false);

  const tabs = [
    {
      key: "home",
      title: "首页",
      icon: <AppOutline />,
      path: "/",
    },
    {
      key: "quick",
      title: "快速刷题",
      icon: <UnorderedListOutline />,
      path: "/quick",
    },
    {
      key: "user",
      title: "我的",
      icon: <UserOutline />,
      path: "/user",
    },
  ];

  // 控制高亮
  const [activeKey, setActiveKey] = useState("quick");

  useLayoutEffect(() => {
    // 解决页面刷新之后，默认值导致的高亮错误问题。
    let index = tabs.findIndex((item) => item.path === location.pathname);
    if (index !== -1) {
      setActiveKey(tabs[index].key);
      setVisiable(true);
    } else {
      setVisiable(false);
    }
  }, [location.pathname]);

  // 当tabbar被点击的时候
  const change = (e: string) => {
    // 设置高亮
    setActiveKey(e);

    // 跳转
    let index = tabs.findIndex((item) => item.key === e);
    navigate(tabs[index].path);
  };

  return (
    <TabBar
      className={styles.qdtabbar}
      style={{
        display: visiable ? "block" : "none",
      }}
      activeKey={activeKey}
      onChange={change}
    >
      {tabs.map((item) => (
        <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
      ))}
    </TabBar>
  );
}
